<template>
  <div class="home">
    <div class="title-container">
      <div class="search-content">
        <el-form :model="searchModel" :inline="true">
          <el-form-item>
            <el-input
              v-model="searchModel.systemCode"
              placeholder="请输入名称"
              prefix-icon="el-icon-search"
            />
          </el-form-item>
        </el-form>
        <div class="search-btn">
          <el-button
            type="primary"
            icon="el-icon-search"
            @click="searchClick"
            size="medium"
          >搜索
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <div class="addAccount">
        <el-button type="primary" icon="el-icon-back" size="medium" @click="goBack()">返回</el-button>
        <perButton label="添加" size="medium" icon="el-icon-plus" perms="PC_SET_PEOPLE_ADD" type="primary"
                   @click="handlerAdd"></perButton>
        <el-button
          type="success"
          icon="el-icon-refresh"
          size="medium"
          @click="refresh"
        >刷新
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%;"
        class="elTable"
      >
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="userName" label="用户姓名" align="center"/>
        <el-table-column prop="userCode" label="用户编号" align="center"/>
        <!-- <el-table-column prop="userPhone" label="登录账号" align="center"/>
        <el-table-column prop="menuCode" label="组织架构" align="center"/>
        <el-table-column prop="menuCode" label="角色属性" align="center"/>
        <el-table-column prop="createByName" label="创建人" align="center"/> -->
        <el-table-column label="创建时间" align="center" prop="createTime">
          <template slot-scope="scope">
            {{ scope.row.createTime }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" align="center">
          <template #default="{ row }">
            <perButton label="分配菜单" type="primary" size="mini" perms="PC_SET_PEOPLE_MENU" @click="settingMenu(row)"></perButton>
            <perButton label="菜单排序" type="primary" size="mini" perms="PC_SET_PEOPLE_MENUSORT" @click="handlerSort(row)"></perButton>
            <perButton label="删除" type="danger" size="mini" perms="PC_SET_PEOPLE_DEL" @click="handlerDelete(row)"></perButton>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        class="pagination"
        :total="count"
        :page.sync="pageIndex"
        :limit.sync="pageSize"
        @pagination="getAccountData"
      />
    </el-card>

    <!-- 新建弹框 -->
    <yc-dialog ref="addDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
          <el-form
            ref="addFormRef"
            :model="addForm"
            inline
            label-width="auto"
          >
            <el-form-item>
              <el-input
                v-model="peopleName"
                placeholder="请输入名称"
                prefix-icon="el-icon-search"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="searchPeople"
                size="medium"
              >查询
              </el-button>
            </el-form-item>
          </el-form>
          <el-table
            :data="peopleList"
            border
            style="width: 100%;"
            class="elTable"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="index" label="序号" width="50" align="center"/>
            <el-table-column prop="userName" label="用户姓名" align="center"/>
            <el-table-column prop="userCode" label="用户编码" align="center"/>
            <el-table-column prop="userPhone" label="手机号" align="center"/>
            <!-- <el-table-column prop="menuCode" label="组织架构" align="center"/>
            <el-table-column prop="menuCode" label="角色属性" align="center"/> -->
            <el-table-column label="操作" type="selection" width="50" align="center" />
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="addLoading" @click="addSave">确定</el-button>
        <el-button @click="$refs.addDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 分配菜单 -->
    <yc-dialog ref="menuDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
          <div class="mb-3" v-for="(item, index) in menuList" :key="index">
            <el-checkbox class="mb-3" :indeterminate="isIndeterminate[index]" v-model="checkAll[index]" @change="handleCheckAllChange($event, index)">{{ item.menuName }}</el-checkbox>
            <el-checkbox-group v-model="checkedMenus[index]" @change="handleCheckedMenusChange($event, index)" v-if="item.children && item.children.length > 0">
              <el-checkbox class="mb-3" v-for="menu in item.children" :label="menu.menuCode" :key="menu.id">{{ menu.menuName }}</el-checkbox>
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="menuLoading" @click="menuSave">确定</el-button>
        <el-button @click="$refs.menuDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 菜单排序弹框 -->
    <yc-dialog ref="sortDialog" :centerTitle="centerTitle" :dialogTitle="dialogTitle">
      <template #content>
        <div class="dialog-content">
          <el-table
            v-loading="loading"
            :data="sortList"
            border
            style="width: 100%;"
            class="sortTable"
            row-key="id"
          >
            <el-table-column type="index" label="序号" width="50" align="center"/>
            <el-table-column prop="menuName" label="菜单名称" align="center"/>
            <el-table-column prop="menuCode" label="菜单编码" align="center"/>
          </el-table>
        </div>
      </template>
      <template #footer>
        <el-button type="primary" :loading="sortLoading" @click="sortSave">确定</el-button>
        <el-button @click="$refs.sortDialog.dialogVisible = false">取消
        </el-button>
      </template>
    </yc-dialog>

    <!-- 封装操作后弹框 -->
    <global-message v-if="isGlobalMessageShow" @receive="receive" :message="message"/>
  </div>
</template>

<script>
  import Sortable from 'sortablejs'
  import ycDialog from "@/components/pageDialog"
  import perButton from "@/components/permissionButton"
  import { queryPage, queryPersonList, insertByModel, deleteByModel, queryPersonMenu, savePersonMenu, queryMenuList, sortMenu } from "@/api/systemBuilding/people"
  import { getBasePic } from "@/api/systemBuilding/pcSystemBuilding"

  export default {
    components: {
      ycDialog,
      perButton,
    },
    data() {
      return {
        isGlobalMessageShow: false,
        message: "",

        systemCode: "",
        tableData: [],
        count: 0,
        pageIndex: 1,
        pageSize: 10,
        loading: false,
        searchModel: {
          menuName: "",
        },

        centerTitle: "",
        dialogTitle: "",
        addLoading: false,
        addForm: {
          peopleList: [],
        },
        peopleName: "",
        peopleList: [],

        isIndeterminate: [],
        checkAll: [],
        checkedMenus: [],
        curRow: {},
        menuList: [],
        menuLoading: false,

        sortLoading: false,
        sortList: [],
      }
    },
    created() {
      this.systemCode = this.$route.query.systemCode;
      this.getAccountData()
      this.searchPeople()
    },
    methods: {
      /**
       * 获取表格方法
       */
      async getAccountData() {
        this.loading = true
        const {object} = await queryPage({
          pageIndex: this.pageIndex,
          pageSize: this.pageSize,
          systemCode: this.systemCode
        })
        this.tableData = object.data
        this.count = object.count
        this.loading = false
      },

      pagination(pageItem) {
        this.getAccountData()
      },

      goBack() {
        this.$router.go(-1)
      },

      // 搜索按钮
      async searchClick() {
        this.getAccountData(this.searchModel)
      },

      /**
       * 刷新
       */
      refresh() {
        this.searchModel = {
          systemCode: "",
        }
        this.getAccountData()
      },

      /**
       * 查询用户
       */
      searchPeople() {
        queryPersonList({
          systemCode: this.systemCode
        }).then(res => {
          if(res.status == 200) {
            this.peopleList = res.object;
          }
        })
      },

      /**
       * 查询菜单
       */
      async searchMenu() {
        const {status, object} = await queryPersonMenu({
          systemCode: this.systemCode
        })
        if(status == 200) {
          this.menuList = object;
          if(this.menuList && this.menuList.length > 0) {
            this.menuList.forEach((item, index) => {
              this.checkedMenus.push([])
              item.children.forEach(menu => {
                if(menu.mapString1 == 1) {
                  this.checkedMenus[index].push(menu.menuCode)
                }
              })

              if(this.checkedMenus[index].length > 0 && this.checkedMenus[index].length == item.children.length) {
                this.checkAll.push(true);
                this.isIndeterminate.push(false);
              } else if(this.checkedMenus[index].length > 0){
                this.checkAll.push(false);
                this.isIndeterminate.push(true);
              } else {
                this.checkAll.push(false);
                this.isIndeterminate.push(false);
              }
            })
          }
        }
      },

      handleSelectionChange(val) {
        this.addForm.peopleList = val;
      },

      /**
       * 新建
       */
      handlerAdd() {
        this.dialogTitle = "添加"
        this.centerTitle = "添加"
        this.$refs.addDialog.dialogVisible = true
        this.addForm.peopleList = []
      },

      /**
       * 新建保存
       */
      addSave() {
        this.$refs.addFormRef.validate(async (v) => {
          if(v) {
            this.addLoading = true;
            let mapString1 = this.addForm.peopleList.map(item => {
              return item.userCode;
            }).join("&")

            const {status, message} = await insertByModel({systemCode: this.systemCode, mapString1: mapString1});
            if (status == 200) {
              this.getAccountData()
              this.$refs.addDialog.dialogVisible = false
              this.$message.success(message)
            }
            this.addLoading = false;
          }
        })
      },

      /**
       * 删除
       */
      handlerDelete(row) {
        this.$confirm("确定删除此菜单吗", "删除操作", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "error",
          center: true
        }).then(async () => {
          const {message, status} = await deleteByModel({
            systemCode: row.systemCode,
            userCode: row.userCode
          })
          if (status == "200") {
            this.getAccountData()
            this.isGlobalMessageShow = true
            this.message = "success"
          } else {
            this.message = "error"
          }
        })
      },


      /**
       * 一级菜单全选
       */
      handleCheckAllChange(val, index) {
        this.checkedMenus[index] = val ? this.menuList[index].children.map(item => {return item.menuCode}) : [];
        this.isIndeterminate[index] = false;
      },

      /**
       * 二级菜单选择事件
       */
      handleCheckedMenusChange(value, index) {
        let checkedCount = value.length;
        this.checkAll[index] = checkedCount === this.menuList[index].children.length;
        this.isIndeterminate[index] = checkedCount > 0 && checkedCount < this.menuList[index].children.length;
        this.$set(this.isIndeterminate, index, this.isIndeterminate[index]);
      },

      /**
       * 分配菜单
       */
      settingMenu(row) {
        this.dialogTitle = "分配菜单"
        this.centerTitle = "分配菜单"
        this.curRow = row;
        this.searchMenu();
        this.$refs.menuDialog.dialogVisible = true
      },

      /**
       * 分配菜单保存
       */
      async menuSave() {
        let mapString1 = this.checkedMenus.map(child => {
          return child.join("&")
        }).join("&")
        if(mapString1) {
          this.menuLoading = true;
          const {message, status} = await savePersonMenu({
            systemCode: this.curRow.systemCode,
            userCode: this.curRow.userCode,
            mapString1: mapString1
          })
        }
        this.menuLoading = false;
        this.$refs.menuDialog.dialogVisible = false
      },

      /**
       * 菜单排序
       */
      async handlerSort(row) {
        this.dialogTitle = "菜单排序"
        this.centerTitle = "菜单排序"
        this.curRow = row;
        this.$refs.sortDialog.dialogVisible = true

        const {object, status} = await queryMenuList({
          systemCode: this.systemCode,
          userCode: row.userCode
        })

        if(status == 200) {
          this.sortList = object;
        }

        this.$nextTick(() => {
          const el = document.querySelector('.sortTable .el-table__body-wrapper table tbody')
          Sortable.create(el, {
            animation: 150,
            handle: '.el-table__row', // 如果需要点击某个图标拖拽的话需要吧那个图标的class写在这里
            onEnd: evt => {
              const curRow = this.sortList.splice(evt.oldIndex, 1)[0];
              this.sortList.splice(evt.newIndex, 0, curRow);
            }
          })
        })
      },

      /**
       * 菜单排序保存
       */
      async sortSave() {
        this.sortLoading = true;
        let mapString1 = this.sortList.map(item => {
          return item.menuCode
        }).join("&");

        const {message, status} = await sortMenu({
          mapString1: mapString1,
          systemCode: this.systemCode,
          userCode: this.curRow.userCode
        })
        if (status == 200) {
          this.getAccountData()
          this.$refs.sortDialog.dialogVisible = false
          this.$message.success(message)
        }
        this.sortLoading = false;
      },

      /**
       * globalMessage的知道按钮的方法
       * */
      receive() {
        this.isGlobalMessageShow = false
      },
    }
  }
</script>

<style lang="scss" scoped>
  .title-container {
    display: flex;
    justify-content: flex-end;
    height: 60px;

    .search-content {
      margin-left: 20px;
      display: flex;
    }

    .addAccount {
      margin: 10px 20px;
    }
  }

  .avatar2 {
    width: 50px;
    height: 50px;
    display: block;
  }

  .pagination {
    display: flex;
    justify-content: flex-end;
  }

  .footer {
    height: 360px;
    display: flex;
    align-items: flex-end;
    padding: 5px 20px;
  }
</style>
